package com.cvmars.jianyou.module.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cvmars.jianyou.R;
import com.cvmars.jianyou.api.api.Api;
import com.cvmars.jianyou.api.api.HttpUtils;
import com.cvmars.jianyou.api.api.SimpleSubscriber;
import com.cvmars.jianyou.api.model.HttpResult;
import com.cvmars.jianyou.config.MyConfig;
import com.cvmars.jianyou.model.ImageUploadModel;
import com.cvmars.jianyou.model.UserInfoManager;
import com.cvmars.jianyou.model.UserModel;
import com.cvmars.jianyou.module.adapter.FindCommentAdapter;
import com.cvmars.jianyou.module.adapter.FindImgAdapter;
import com.cvmars.jianyou.module.base.BaseActivity;
import com.cvmars.jianyou.module.base.BaseImagePagerActivity;
import com.cvmars.jianyou.module.model.DianZhanModel;
import com.cvmars.jianyou.module.model.EventFindRefresh;
import com.cvmars.jianyou.module.model.FindCommentList;
import com.cvmars.jianyou.module.model.FindCommentModel;
import com.cvmars.jianyou.module.model.FindModel;
import com.cvmars.jianyou.module.model.TopicModel;
import com.cvmars.jianyou.ui.CircleImageView;
import com.cvmars.jianyou.utils.ClickUtils;
import com.cvmars.jianyou.utils.DensityUtils;
import com.cvmars.jianyou.utils.ImageUtils;
import com.cvmars.jianyou.utils.KeyBoradUtils;
import com.cvmars.jianyou.utils.ToastUtils;
import com.cvmars.jianyou.utils.UtilHelper;
import com.cvmars.jianyou.widget.KeyboardChangeListener;
import com.cvmars.jianyou.widget.NoScrollListView;
import com.sackcentury.shinebuttonlib.ShineButton;
import com.wx.goodview.GoodView;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class FindDetailActivity extends BaseActivity {


    FindModel model;
    @BindView(R.id.findUserName)
    TextView findUserName;
    @BindView(R.id.find_time)
    TextView findTime;
    @BindView(R.id.findheadImg)
    CircleImageView findheadImg;
    @BindView(R.id.findContent)
    TextView findContent;
    @BindView(R.id.findContents)
    LinearLayout findContents;
    @BindView(R.id.find_grid)
    RecyclerView findGrid;

    @BindView(R.id.iv_image)
    ImageView ivImage;
    @BindView(R.id.find_delete)
    ImageView findDelete;
    @BindView(R.id.iv_sex)
    ImageView ivSex;
    @BindView(R.id.iv_vip)
    ImageView iv_love;
    @BindView(R.id.find_address)
    TextView findAddress;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.txt_send)
    TextView txtSend;
    @BindView(R.id.nicename)
    TextView nicename;
    @BindView(R.id.find_time_ni)
    TextView findTimeNi;
    @BindView(R.id.rl_nickname)
    RelativeLayout rlNickname;
    @BindView(R.id.rl_info)
    RelativeLayout rlInfo;
    @BindView(R.id.rl_image)
    RelativeLayout rlImage;
    @BindView(R.id.txt_tuiguang)
    TextView txtTuiguang;
    @BindView(R.id.txt_prise)
    TextView txtPrise;
    @BindView(R.id.txt_number)
    ShineButton txt_number;
    @BindView(R.id.list_comment)
    NoScrollListView listComment;
    FindCommentAdapter commentAdapter;
    @BindView(R.id.sl_detail)
    ScrollView slDetail;

    List<FindCommentModel> commentModels = new ArrayList<>();
    @BindView(R.id.txt_comment_number)
    TextView txtCommentNumber;
    @BindView(R.id.ll_dianzhan)
    LinearLayout llDianzhan;
    @BindView(R.id.ll_comment)
    LinearLayout llComment;

    private String commentID;

    DianZhanModel modelDianZhan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_detail);
        ButterKnife.bind(this);

        modelDianZhan = new DianZhanModel();
        model = (FindModel) getIntent().getSerializableExtra("data");
        String mFindID = getIntent().getStringExtra("find");
        if (!TextUtils.isEmpty(mFindID)) {

            modelDianZhan.find_id = mFindID;
            getFindDetail(mFindID);
        } else {

            initData();
        }

        commentAdapter = new FindCommentAdapter(this);
        listComment.setAdapter(commentAdapter);


        slDetail.post(new Runnable() {
            @Override
            public void run() {

                slDetail.scrollTo(0, 0);
            }
        });


        KeyboardChangeListener softKeyboardStateHelper = new KeyboardChangeListener(this);
        softKeyboardStateHelper.setKeyBoardListener(new KeyboardChangeListener.KeyBoardListener() {
            @Override
            public void onKeyboardChange(boolean isShow, int keyboardHeight) {
                if (isShow) {
                    //键盘的弹出

                } else {
                    //键盘的收起
                    etContent.setHint("评论");
                    commentID = "";
                    etContent.setText("");
                }
            }
        });

        listComment.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {


                if (!UserInfoManager.getInstance().isOneSelf(commentModels.get(i).from_customer.id)) {

                    commentID = commentModels.get(i).id + "";
                    etContent.setHint("评论" + commentModels.get(i).from_customer.name + "：");

                    KeyBoradUtils.openKeyborad(etContent, FindDetailActivity.this);
                }
            }
        });

        commentAdapter.setOnDelete(new FindCommentAdapter.OnClickDeleteListener() {
            @Override
            public void onDelete(final String commID) {


                onDeleteComment(commID);

            }
        });
    }

    private void onDeleteComment(String commentIDs) {


        HttpUtils.getInstance().toSubscribe(Api.getInstance().deleteFindComment(commentIDs)
                , new SimpleSubscriber<HttpResult<Object>>() {
                    @Override
                    protected void _onNext(HttpResult<Object> o) {

                        onRequestCommentList();
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }

    private void avoidHintColor(View view) {
        if (view instanceof TextView)
            ((TextView) view).setHighlightColor(getResources().getColor(android.R.color.transparent));
    }

    private void initData() {

        findheadImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                onGoHome(model.customer.id);
            }
        });

        if (model != null) {

            initData(model);
        }
        onRequestCommentList();
        onRequestDianZhanList();

        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                if (charSequence.length() == 0) {

                    txtSend.setTextColor(ContextCompat.getColor(FindDetailActivity.this, R.color.color333));

                    txtSend.setBackgroundResource(R.drawable.shape_send);
                } else {

                    txtSend.setTextColor(Color.WHITE);
                    txtSend.setBackgroundResource(R.drawable.shape_send_select);

                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
        findDelete.setVisibility(View.GONE);
    }

    private void initData(FindModel model) {

        findContent.setText(model.text);
        if (model.comment_total != 0) {
            txtCommentNumber.setText("最新评论 " + model.comment_total);
        }
        findTime.setText(UtilHelper.forumFriendlyTime(model.create_at));
        findTimeNi.setText(UtilHelper.forumFriendlyTime(model.create_at));
        modelDianZhan.find_id = model.id;
        modelDianZhan.comments = model.comment_total;
        modelDianZhan.likes = model.like_total;
        modelDianZhan.is_like = model.is_like;

        txt_number.setChecked(model.is_like);
        UserModel customer = model.customer;
        rlInfo.setVisibility(!model.is_hidden_name ? View.VISIBLE : View.GONE);
        rlNickname.setVisibility(model.is_hidden_name ? View.VISIBLE : View.GONE);
        iv_love.setVisibility(model.customer.is_rut ? View.VISIBLE : View.GONE);
//        txtTuiguang.setVisibility(model.isNick ? View.VISIBLE : View.GONE);

        final List<TopicModel> topic = model.topic;

        if(topic!=null && topic.size() > 0){
            txtTuiguang.setVisibility(View.VISIBLE);
            txtTuiguang.setText("#"+model.topic.get(0).name +"#");
        }else{
            txtTuiguang.setVisibility(View.GONE);
        }

        txtTuiguang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(FindDetailActivity.this, FindTopicActivity.class);
                intent.putExtra("model",topic.get(0));
                startActivity(intent);
            }
        });

        if (customer != null) {

            ImageUtils.loadImage(this, customer.avatar_url, findheadImg);
            findUserName.setText(customer.name);
            nicename.setText("@" + customer.address_home + "的娃");
            findAddress.setText(customer.address_home);

            ivSex.setImageResource(customer.gender == 1 ? R.drawable.ic_male : R.drawable.ic_women);
            if (UserInfoManager.getInstance().isOneSelf(customer.id)) {
                findDelete.setVisibility(View.VISIBLE);
            }
        }

        final List<ImageUploadModel> images = model.images;

        if (images != null) {

            if (images.size() > 1) {

                FindImgAdapter imgAdapter = new FindImgAdapter(this, R.layout.item_find_img, images);

                imgAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                        Bundle bundle = new Bundle();
                        bundle.putSerializable(MyConfig.INTENT_DATA_URL, (Serializable) images);
                        Intent intent = new Intent(FindDetailActivity.this, BaseImagePagerActivity.class);
                        intent.putExtra("position", position);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });
                findGrid.setLayoutManager(new GridLayoutManager(this, 3));
//                gridView.addItemDecoration(new SpacesItemDecoration(DensityUtils.dip2px(mContext, 3)));
                findGrid.setAdapter(imgAdapter);
            } else if (images.size() == 1) {
                findGrid.setVisibility(View.GONE);
                ivImage.setVisibility(View.VISIBLE);
                ImageUtils.loadImage(this, images.get(0).url, ivImage);


                int width = Integer.parseInt(images.get(0).w);
                int height = Integer.parseInt(images.get(0).h);
                if(height!=0 && width!=0) {
                    if (width > height) {
                        ivImage.getLayoutParams().width = DensityUtils.dp2px(this, 180);
                        ivImage.getLayoutParams().height = DensityUtils.dp2px(this, 180) * height / width;

                    } else {

                        ivImage.getLayoutParams().height = DensityUtils.dp2px(this, 180);
                        ivImage.getLayoutParams().width = DensityUtils.dp2px(this, 180) * width / height;

                    }
                }

                ivImage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        Bundle bundle = new Bundle();
                        bundle.putSerializable(MyConfig.INTENT_DATA_URL, (Serializable) images);
                        Intent intent = new Intent(FindDetailActivity.this, BaseImagePagerActivity.class);
                        intent.putExtra("position", 0);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });
            } else {

                rlImage.setVisibility(View.GONE);
            }
        } else {

            rlImage.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.find_delete, R.id.txt_send})
    public void onViewClicked(View view) {

        switch (view.getId()) {

            case R.id.find_delete:


                new AlertDialog.Builder(FindDetailActivity.this).setMessage("是否删除动态？").setTitle("")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {


                                onDelete();
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                    }
                }).show();
                break;


            case R.id.txt_send:

                onAddComment();
                break;
        }


    }


    private void onDelete() {

        HttpUtils.getInstance().toSubscribe(Api.getInstance().deleteFind(model.id)
                , new SimpleSubscriber<HttpResult<Object>>() {
                    @Override
                    protected void _onNext(HttpResult<Object> o) {

                        ToastUtils.show("删除成功");
                        EventBus.getDefault().post(new EventFindRefresh(true));
                        finish();
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }

    private void getFindDetail(String detailID) {

        HttpUtils.getInstance().toSubscribe(Api.getInstance().getFindDetail(detailID)
                , new SimpleSubscriber<HttpResult<FindModel>>() {
                    @Override
                    protected void _onNext(HttpResult<FindModel> o) {

                        getLoadDialogAndDismiss();
                        model = o.getData();
                        initData();
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }


    private void onRequestDianZhanList() {


        HttpUtils.getInstance().toSubscribe(Api.getInstance().getFindDianzhanList(model.id)
                , new SimpleSubscriber<HttpResult<FindCommentList>>() {
                    @Override
                    protected void _onNext(HttpResult<FindCommentList> o) {

                        FindCommentList data = o.getData();

                        modelDianZhan.likes = Integer.parseInt(data.count);
                        EventBus.getDefault().post(modelDianZhan);

                        llDianzhan.setVisibility(!"0".equals(data.count) ? View.VISIBLE : View.GONE);

                        if (data != null) {

                            List<FindCommentModel> result = data.results;


                            if (result != null && result.size() != 0) {

                                String resultStr = "";

                                for (int i = 0; i < result.size(); i++) {

                                    resultStr = resultStr + result.get(i).customer.name + " ";
                                }

                                SpannableStringBuilder builder = new SpannableStringBuilder(resultStr);

                                int length = 0;
                                for (int i = 0; i < result.size(); i++) {

                                    builder.setSpan(new ClickableSpan() {
                                        @Override
                                        public void onClick(View widget) {
                                            avoidHintColor(widget);
                                        }

                                        @Override
                                        public void updateDrawState(TextPaint ds) {
                                            super.updateDrawState(ds);
                                            ds.setColor(getResources().getColor(R.color.m5));
                                            ds.setUnderlineText(false);
                                            ds.clearShadowLayer();
                                        }
                                    }, length, length + result.get(i).customer.name.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                                    length = length + result.get(i).customer.name.length() + 1;
                                }

                                txtPrise.setText(builder);
                                txtPrise.setMovementMethod(LinkMovementMethod.getInstance());

                            }
                        }
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });


    }


    private void onRequestCommentList() {


        HttpUtils.getInstance().toSubscribe(Api.getInstance().getFindCommentList(model.id)
                , new SimpleSubscriber<HttpResult<FindCommentList>>() {
                    @Override
                    protected void _onNext(HttpResult<FindCommentList> o) {

                        FindCommentList data = o.getData();
                        llComment.setVisibility(View.VISIBLE);

                        modelDianZhan.comments = Integer.parseInt(data.count);
                        EventBus.getDefault().post(modelDianZhan);

                        if (!"0".equals(data.count)) {

                            txtCommentNumber.setText("最新评论 " + data.count);
                        } else {

                            txtCommentNumber.setText("最新评论 ");
                        }
                        if (data != null) {

                            List<FindCommentModel> result = data.results;


                            if (result != null) {
                                commentModels.clear();
                                commentModels.addAll(result);
                                commentAdapter.setCommentModels(commentModels);
                            }
                        }
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });


    }


    private void onAddComment() {

        String content = etContent.getText().toString();

        if (!ClickUtils.isNotFastClick()) {

            return;
        }
        if (TextUtils.isEmpty(commentID)) {
            if (TextUtils.isEmpty(content)) {

                ToastUtils.show("内容不能为空");
                return;
            }
            HttpUtils.getInstance().toSubscribe(Api.getInstance().postFindComment(model.id, content)
                    , new SimpleSubscriber<HttpResult<Object>>() {
                        @Override
                        protected void _onNext(HttpResult<Object> o) {




                            ToastUtils.show(o.getMsg());
                            etContent.setText("");
                            KeyBoradUtils.closeKeyborad(etContent, FindDetailActivity.this);
                            onRequestCommentList();
                        }

                        @Override
                        protected void _onError(String message) {

                        }
                    });
        } else {
            HttpUtils.getInstance().toSubscribe(Api.getInstance().postFindCommentPerson(commentID, content)
                    , new SimpleSubscriber<HttpResult<Object>>() {
                        @Override
                        protected void _onNext(HttpResult<Object> o) {

                            ToastUtils.show(o.getMsg());
                            etContent.setText("");
                            etContent.setHint("评论");
                            KeyBoradUtils.closeKeyborad(etContent, FindDetailActivity.this);
                            onRequestCommentList();
                        }

                        @Override
                        protected void _onError(String message) {

                        }
                    });
        }


    }


    private void onGoHome(String id) {

        Intent intent = new Intent(this,
                PersonHomeActivity.class);
        intent.putExtra("userid", id);
        startActivity(intent);
    }

    @OnClick(R.id.txt_number)
    public void onViewClicked() {

        onAddDianzhan();
    }


    private void onAddDianzhan() {

        HttpUtils.getInstance().toSubscribe(Api.getInstance().postPriseFind(model.id, "")
                , new SimpleSubscriber<HttpResult<Object>>() {
                    @Override
                    protected void _onNext(HttpResult<Object> o) {

                        modelDianZhan.is_like = true;
                        EventBus.getDefault().post(modelDianZhan);


                        final GoodView goodView = new GoodView(FindDetailActivity.this);
                        goodView.setTextInfo("+1", ContextCompat.getColor(FindDetailActivity.this, R.color.colorAccent), 12);
                        goodView.show(findViewById(R.id.txt_number));
                        onRequestDianZhanList();
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });

    }
}
